package com.csp.mingyue.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csp.mingyue.system.api.entity.SysRole;
import com.csp.mingyue.system.api.entity.SysUserRole;
import com.csp.mingyue.system.mapper.SysRoleMapper;
import com.csp.mingyue.system.service.SysRoleService;
import com.csp.mingyue.system.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author njy
 * @since 2023-07-21 10:04:39
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

	private final SysRoleMapper sysRoleMapper;

	private final SysUserRoleService sysUserRoleService;

	@Override
	public Set<String> getRolePermission(Long userId) {
		List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
		if (CollectionUtil.isNotEmpty(sysRoles)) {
			return sysRoles.stream().map(SysRole::getRoleCode).collect(Collectors.toSet());
		}

		return null;
	}

	@Override
	public boolean addUserRole(Long userId, String roleCode) {
		// 获取角色信息
		SysRole sysRole = this.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleCode, roleCode));

		if (Objects.isNull(sysRole)) {
			return Boolean.FALSE;
		}

		SysUserRole sysUserRole = new SysUserRole();
		sysUserRole.setUserId(userId);
		sysUserRole.setRoleId(sysRole.getRoleId());

		return sysUserRoleService.save(sysUserRole);
	}

}
